#include"Socket.hpp"
using service_io_t = function<void(SockSPtr, InetAddr&)>;
class TcpServer
{
public:
    TcpServer(service_io_t service,uint16_t port=gport):_listensock(make_shared<TcpSocket>(gport)),_service(service)
    {
        _listensock->BuildListenSocket();
    }
    class ThreadDate
    {
    public:
    ThreadDate(SockSPtr sockfd,TcpServer* self,const InetAddr& addr):_sockfd(sockfd),_self(self),_addr(addr)
    {}
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;
    };
   
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            SockSPtr newsock=_listensock->Accepter(&client);
            LOG(INFO, "new connect %s\n", client.Ip().c_str());
            if(newsock==nullptr)
                continue;
            // 多线程版本
            pthread_t tid;
            ThreadDate *td = new ThreadDate(newsock, this,client);
            pthread_create(&tid, nullptr, Excute, td);
        }
    }
    static void* Excute(void* args)
    {
        pthread_detach(pthread_self());
        ThreadDate *td = static_cast<ThreadDate *>(args);
        td->_self->_service(td->_sockfd,td->_addr);
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {}

private:
    SockSPtr _listensock;
    bool _isrunning = false;
    service_io_t _service;
};